<?php

namespace app\common\model;

use fast\Random;
use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        if (!$data['avatar']) {
            //如果不需要启用首字母头像，请使用
            $data['avatar'] = '/assets/img/avatar.png';
        }
        return $data['avatar'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            $value = '/assets/img/avatar.png';
            //$value = letter_avatar($data['nickname']);
        }
        $value = get_full_img($value);
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 获取6位数推广码
     * @return int
     */
    public static function unique_code()
    {
        $number = rand(10000000, 99999999);
        if (self::get(['uniquecode' => $number])) {
            return self::unique_code();
        } else {
            return $number;
        }
    }

    /**
     * 获取推荐人id
     * @param $uniquecode
     * @return int
     */
    public static function superior_uid($uniquecode)
    {
        //$uniquecode=substr($uniquecode, 0, 6);
        $uniquecode = trim($uniquecode);
        if ($uniquecode && $superior = self::get(['uniquecode' => $uniquecode])) {
            return $superior['id'];
        } else {
            return 0;
        }
    }

    /**
     * 根据手机号获取或创建用户
     * @param $mobile
     * @return mixed
     */
    public static function getOrCreate($mobile)
    {
        $username = $mobile;
        $password = Random::alnum();
        $uniquecode = self::unique_code();
        $extend = ['uniquecode' => $uniquecode];
        $email = '';
        $user = self::getByMobile($mobile);
        if ($user) return $user['id'];

        $ip = request()->ip();
        $time = time();

        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'mobile' => $mobile,
            'level' => 1,
            'score' => 0,
            'avatar' => '',
        ];
        $params = array_merge($data, [
            'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
            'salt' => Random::alnum(),
            'jointime' => $time,
            'joinip' => $ip,
            'logintime' => $time,
            'loginip' => $ip,
            'prevtime' => $time,
            'status' => 'normal'
        ]);
        $params['password'] = self::getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);
        $user = User::create($params, true);
        return $user->id;
    }

    public static function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 获取优惠券
     * @param $user_id
     * @param $price
     * @param $expiredtime
     * @param int $limit
     * @param int $shop_id
     * @param string $remark
     * @return UserCoupon
     */
    public static function receive_coupon($user_id, $price, $starttime, $expiredtime, $limit = 0, $way = 'receive', $shop_id = 0, $coupon_id = 0)
    {
        return UserCoupon::create(compact('user_id', 'price', 'starttime', 'expiredtime', 'limit', 'way', 'shop_id', 'coupon_id'));
    }

}
